<?php
// WebSocketServer.php
namespace app\WebSocket;

use app\api\service\BroadcastService;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use SplObjectStorage;
class WebSocketServer implements MessageComponentInterface{
    protected $broadcastService;

    public function __construct() {
        $this->broadcastService = new BroadcastService(); // 初始化广播服务
    }

    public function onOpen(ConnectionInterface $conn) {
        $query = $conn->httpRequest->getUri()->getQuery();
        parse_str($query, $output);
        $userId = $output['user_id'] ?? null;

        $this->broadcastService->addClient($conn,$userId);
        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        echo "Received message: $msg\n";

        // 尝试解析消息为 JSON 格式
        $data = json_decode($msg, true);

        if (isset($data['target_user_id'])) {
            // 发送给指定用户
            $targetUserId = $data['target_user_id'];
//            $message = $data['message'] ?? 'No message'; // 获取消息内容

            $this->broadcastService->sendToUserById($targetUserId, $msg);
        } else {
            // 没有指定用户 ID，进行广播
            $this->broadcastService->broadcast($msg);
        }
    }

    public function onClose(ConnectionInterface $conn) {
        $this->broadcastService->removeClient($conn);
        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }


}
